import { fetchList, queryList } from "@/api/article";
import { fetchArticle } from "@/api/server";

const articles = {
    state: {
        searchKey: "",
        searchLabel: "",
        showList: true,
        list: [],
    },
    mutations: {
        SET_SHOW_LIST: (state, val) => {
            state.showList = val;
        },
        ADD_ARTICLE: (state, val) => {
            state.list.splice(state.list.findIndex(item => item.id === val.id), 1)
            state.list.push(val);
        },
        SET_SEARCHKEY: (state, val) => {
            state.searchKey = val;
        },
        SET_SEARCHLABEL: (state, val) => {
            state.searchLabel = val;
        },
        SET_ARTICLES: (state, val) => {
            state.list = val;
        },
        FIND_ARTICLE: (state, val) => {
            return state.list.find(item => item.id = val);
        },
        DEL_ALL_ARTICLES: (state) => {
            state.list = []
        }
    },
    actions: {
        fetchShowList({ commit, dispatch, state }, props) {
            return fetchList(props).then(res => {
                commit('SET_ARTICLES', res.data)
            })
        },
        queryShowList({ commit, dispatch, state }, props) {
            return queryList(props).then(res => {
                commit('SET_ARTICLES', res.data)
            })
        },
        fetchShowArticle({ commit }, params) {
            return fetchArticle(params).then(res => commit('ADD_ARTICLE', res.data))
        },
        setShowList({ commit }, val) {
            commit('SET_SHOW_LIST', val)
        },
        setSearchLabel({ commit }, val) {
            commit('SET_SEARCHLABEL', val)
        },
        setSearchKey({ commit }, val) {
            commit('SET_SEARCHKEY', val)
        },
        setArticles({ commit }, val) {
            commit('SET_ARTICLES', val)
        },
        findArticle({ commit, state }, val) {
            return new Promise((resolve) => {
                resolve(commit('FIND_ARTICLE', val))
            })
        },
        delAllArticles({ commit, state }) {
            return new Promise((resolve) => {
                commit('DEL_ALL_ARTICLES')
                resolve([...state.list])
            })
        }
    }
}

export default articles
